<?php

namespace app\api\model;

use app\admin\model\hotel\Cate;
use app\admin\model\vip\Card;
use think\Model;

/**
 * Hotel
 */
class HitHotel extends Model
{
    // 表名
    protected $name = 'hit_hotel';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $append = [
        'CateName',
        'VipCardName',
    ];




    public function getCateNameAttr($value, $row): array
    {
        return Cate::whereIn('id', $row['hotel_cate_ids'])->column('name');
    }

    public function getVipCardNameAttr($value, $row): array
    {
        return Card::whereIn('id', $row['vip_card_ids'])->column('name');
    }

    protected static function onAfterInsert($model): void
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    public function getRmHotel($params)
    {
        $search = $params['search'] ?? '';
        $map[] = ['rm.status','=',1];
        $map[] = ['h.status','=',1];
        if($search){
            $map[] = ['h.name','like',"%".$search."%"];
        }
        $list = self::alias('rm')
            ->join('hotel h', 'h.id = rm.hotel_id')
            ->where($map)
            ->field('rm.hotel_id,h.name,h.cover,h.address,hotel_cate_ids,vip_card_ids,h.city_name')
            ->order('rm.weigh desc')
            ->paginate(10)->toArray();
        if ($list['total'] == 0) {
            return api_message($list);
        }
        foreach ($list['data'] as &$val) {
            $val['cover'] = full_url($val['cover']);
            unset($val['hotel_cate_ids'],$val['vip_card_ids']);
        }
        return api_message($list);
    }
}